package com.wo2record.base.service.impl;

import java.util.List;

import org.hibernate.Query;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;

import com.wo2record.base.model.BaseModel;
import com.wo2record.base.service.BaseService;

public abstract class BaseServiceAbstractImpl<T extends BaseModel> implements BaseService<T> {
	@Autowired
	private SessionFactory sessionFactory;
	
	private Class<?> objectClass = getObjectClass();
	
	public abstract Class<?> getObjectClass();
	
	@Transactional
	public T saveObject(T t) throws Exception{
		validateObjectBeforeSave(t);
		sessionFactory.getCurrentSession().saveOrUpdate(t);
		return t;
	}
	
	@Transactional
	public T getObject(String id){
		T t = (T)sessionFactory.getCurrentSession().get(objectClass, id);
		return t;
	}
	
	@Transactional
	public List<T> getObjects(){
		Query query = sessionFactory.getCurrentSession().createQuery("from " + objectClass.getName());
		return query.list();
	}
	
	public List<T> getObjects(String hql){
		Query query = sessionFactory.getCurrentSession().createQuery(hql);
		return query.list();
	}
	
	public abstract void validateObjectBeforeSave(T t) throws Exception;
}
